<?php
namespace PsiFramework\Applications\AlloMediaUser\Classes\Actions;

use \PsiFramework\Classes\Util\UI\LanguageManager;

import("Applications.AlloMediaUser.Classes.Actions.ShopAction");
import("Classes.Util.HTTP.AuthenticationManager");
import("Classes.Factory.DAOFactory");
import("Classes.Util.Manager.ObjectManager");

use \PsiFramework\Applications\AlloMediaUser\Classes\Actions\ShopAction;
use \PsiFramework\Applications\AlloMediaPortal\Classes\Model\InformationPart;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Classes\Util\HTTP\AuthenticationManager;
use \PsiFramework\Classes\Util\Parameters\Action\ActionParameters;
use \PsiFramework\Classes\Util\Manager\ObjectManager;
use \PsiFramework\Classes\Util\UI\ModuleManager;
use \PsiFramework\Plugins\Form\Classes\DAO\FormResponseDAO;
use \PsiFramework\Plugins\Form\Classes\Util\FormUtil;
use \PsiFramework\Classes\Util\UI\TemplateManager;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * Classe d'action de l'index
 *
 * @package Actions.Pages
 */
class AlloMediaEditProfile extends ShopAction
{

    public function __construct(ActionParameters $actionParameters)
    {
        parent::__construct($actionParameters);
    }

    /**
     * The main function of the method which is called every time
     * an action is created by the front controller.
     *
     */
    public function execute()
    {
        parent::execute();

        TemplateManager::getInstance()->addFileScript(
            'Applications/DefaultApp/Template/scripts/jquery.mousewheel.js'
		);
        
        
        TemplateManager::getInstance()->addFileScript(
            'Applications/DefaultApp/Template/scripts/jquery.alerts.js'
		);
        
        TemplateManager::getInstance()->addFileStyle(
            'Applications/DefaultApp/Template/styles/jquery.alerts.css'
        );
        
        $languageManager = LanguageManager::getInstance();
        
        TemplateManager::getInstance()->addLitteralScript(
            "
            var initialSerializedForm ;
            var editFormValidated = false;
            
            $(document).ready(function(){
                initialSerializedForm = $(\".editForm\").serialize();
                    
                $(\".editForm\").bind('submit', function() {
                  editFormValidated = true;
                });
                    
                $('a').click(function(){
                    var finalSerializedForm = $(\".editForm\").serialize();
                    var target = this;
                    var href = $(target).attr('href');
                    
            		if (initialSerializedForm != finalSerializedForm){
                        $.alerts.okButton = '".$languageManager->getText('YES')."';
                        $.alerts.cancelButton = '".$languageManager->getText('NO')."';
                        jConfirm('".$languageManager->getText('SAVE_CONFIRMATION_TEXT')."', '".$languageManager->getText('SAVE_CONFIRMATION_TITLE')."', function(r) {
                            if(r) {
                                if (!$(target).hasClass('popup')) {
                                    $('<input>').attr({
                                        type: 'hidden',
                                        name: 'redirect',
                                        value: href
                                    }).appendTo('.editForm');
                                }
                                $(\".editForm\").submit();
                                if ($(target).hasClass('popup')) {
                                    window.open(href);
                                }
                            } else {
                                editFormValidated = true;
                                window.location.href = target.href;
                            }
                        });
                        
                        return false;
                                
                    } else if ($(target).hasClass('popup')) {
                        window.open(href);
                        return false;
                    }
                });
                
                $(window).bind('beforeunload', function() {   
                    var finalSerializedForm = $(\".editForm\").serialize();
                        
            		if (!editFormValidated && initialSerializedForm != finalSerializedForm) {
                        return 'LEAVE_PAGE';
                    }
                });
            });
        ");
        
        $formId = $this->_request->getParameter('form_id');
        $form = null ;

        if (!isNullOrEmptyString($formId) && is_numeric($formId)) {
            $formDao = DAOFactory::getDAO('Form');
            $form = $formDao->retrieveByPk($formId);
        }

        $this->_response->setAttribute("form", $form);

        ModuleManager::getInstance()->addModule('LeftMenu', $this->_response);
        ObjectManager::getInstance()->getPrimitiveObjectDaoInstance('Date')->
                                      javascript();

        if (isNullOrEmptyString($form)) {
            $this->_response->setAttribute("formId", $formId);
            $this->findForward($formId);
        } else {
            //HTML::addValidator();
            
            $entry = $this->_response->getAttribute("entry");
            $theme = $form;
            $category = $this->_response->getAttribute("category");
            if (is_null($category) && !is_null($entry)) {
            	$category = $entry->getCategory();
            }
            
            $jsonForm = null ;
            $formResponse = null ;
            $formResponseParameters = $theme->getResponseParameters();
            $responseId = null;
            
            $structure = $theme->getStructure();
            if (!is_null($structure)) {
            
            	$jsonForm = $structure ;
            
            	$responseIdDao = DAOFactory::getDAO('ResponseId');
            	$responseId = $responseIdDao->retrieveByEntryAndTheme($entry, $theme);
            
            	$formResponses = null ;
            	if (!is_null($responseId)) {
            		$formResponseDao = FormResponseDAO::getInstance($formResponseParameters);
            		$formResponse = $formResponseDao->retrieveByPk(
        				$responseId->getId(),
        				false,
        				true,
        				$responseId->getEntry()->getUser(),
        				$theme
            		);
            
            		$formResponses = $formResponseDao->retrieveByUser($entry->getUser());
            	}
            }
            
            $part = null;
            if (!is_null($jsonForm)) {
                $samplePart = new InformationPart();
                $samplePart->setTheme($theme);
                $samplePart->setProfile($category->getprofile());
                $informationPartDao = DAOFactory::getDAO('InformationPart');
                $part = $informationPartDao->retrieveByPk($samplePart->getId());
            }
            
            $editable = true;
            if (!is_null($part)
                && !is_null($responseId)
                && !$responseId->isActive()
                && !$part->isFree()
            ) {
            	$editable = false ;
            }
            
            $formContent = FormUtil::showForm($jsonForm, $formResponseParameters, $formResponse, $editable);
            
            $this->_response->setAttribute("jsonForm", $jsonForm);
            $this->_response->setAttribute("formResponse", $formResponse);
            $this->_response->setAttribute("formResponses", $formResponses);
            $this->_response->setAttribute("formResponseParameters", $formResponseParameters);
            $this->_response->setAttribute("responseId", $responseId);
            $this->_response->setAttribute("structure", $structure);
            $this->_response->setAttribute("part", $part);
            $this->_response->setAttribute("formContent", $formContent);
            
            $this->findForward("theme");
        }
    }
}
